<template>
  <div class="login-body">
    <div class="login-panel">
      <el-form class="login-register"
               :model="formData"
               :rules="rules"
               ref="formDataRef"
               @submit.prevent
      >
        <div class="login-title">骁合云盘</div>
        <!--邮箱输入-->
        <el-form-item prop="email">
          <el-input
              size="large"
              clearable
              placeholder="请输入邮箱"
              v-model.trim="formData.email"
              maxlength="150"
          >
            <template #prefix>
              <span class="iconfont icon-account"></span>
            </template>
          </el-input>
        </el-form-item>

        <!--注册-->
        <div>

          <!--昵称-->
          <el-form-item prop="nickName">
            <el-input
                size="large"
                placeholder="请输入昵称"
                v-model="formData.nickName"
                maxlength="20"
            >
              <template #prefix>
                <span class="iconfont icon-account"></span>
              </template>
            </el-input>
          </el-form-item>
          <!--注册密码-->
          <el-form-item prop="password">
            <el-input
                type="password"
                size="large"
                placeholder="请输入密码"
                show-password
                v-model.trim="formData.password"
            >
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
            </el-input>
          </el-form-item>
          <!--重复密码-->
          <el-form-item prop="cpassword">
            <el-input
                type="password"
                size="large"
                placeholder="请再次输入密码"
                show-password
                v-model.trim="formData.cpassword"
            >
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
            </el-input>
          </el-form-item>
           <!-- 邮箱验证码-->
          <el-form-item prop="emailCode">
            <div class="send-email-panel">
              <el-input
                  size="large"
                  placeholder="请输入邮箱验证码"
                  v-model="formData.emailCode"
              >
                <template #prefix>
                  <span class="iconfont icon-checkcode"></span>
                </template>
              </el-input>
              <el-button class="send-mail-btn" type="primary" size="medium" @click="getEmailCode()">
                获取验证码
              </el-button>
            </div>
          </el-form-item>
        </div>

        <el-form-item >
          <a href="javascript:void(0)" class="a-link" @click="navigateTo('/login')"
          >已有账号？</a>
        </el-form-item>
        <!--注册按钮-->
        <el-form-item>
          <el-button type="primary" class="op-btn" size="medium" @click="Register()">
            <span>注册</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, getCurrentInstance, nextTick} from "vue";
import router from "@/router/index.js";
import {getEmail, register} from "@/api/login.js";
const { proxy } = getCurrentInstance();


const navigateTo = path => router.push(path);

//表单对象
const formData = ref({});
const formDataRef = ref();
//校验规则
const rules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入邮箱地址'));
        }
        const qqRegex = /^[\w-]+(\.[\w-]+)*@qq\.com$/;
        const neteaseRegex = /^[\w-]+(\.[\w-]+)*@(163|126|yeah)\.com$/;

        if (qqRegex.test(value) || neteaseRegex.test(value)) {
          callback(); // 验证通过
        } else {
          callback(new Error('请输入有效的QQ邮箱或网易邮箱'));
        }
      },
      trigger: 'blur'
    }
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 10, message: '昵称长度在 2 到 10 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入密码'));
        }
        const regex = /^(?=.*\d)(?=.*[a-zA-Z]).{6,}$/;
        if (!regex.test(value)) {
          callback(new Error('密码必须包含至少一个数字和一个字母，且长度至少为6位'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  cpassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== formData.value.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

//跳转到登录界面
const toLogin=()=>{
  router.push('/login').then(() => {
    // 强制刷新页面
    window.location.reload();
  });
}
//获取验证码
const getEmailCode = () =>{
    console.log("点击获取验证码,表单对象为：", formData.value);
    formDataRef.value.validate((valid) => {
      if(!valid){
        proxy.$message({
          message:"请检查输入",
          type:'warning'
        })
        return;
      }
      const data={
        username:formData.value.email,
        password:formData.value.password,
        cpassword:formData.value.cpassword
      }

      getEmail(data).then(res=>{
        console.log(res.data);
        if(res.data.code===200){
          proxy.$message({
            message:res.data.msg,
            type:'success'
          })
        }
        else if(res.data.code===500){
          proxy.$message({
            message:res.data.msg,
            type:"warning"
          })
        }
      }).catch((error)=>{
        console.log(error);
      })
    })
}

//注册
const Register = () => {
  formDataRef.value.validate((valid) => {
    if (valid) {
      const data={
        username:formData.value.email,
        password:formData.value.password,
        cpassword:formData.value.cpassword,
        name:formData.value.nickName,
        verificationCode:formData.value.emailCode
      }
      register(data).then((res)=>{
        console.log(res.data);
        if(res.data.code===200){
          proxy.$message({
            message:"注册成功，请前往登录",
            type:'success'
          })
          navigateTo('/login');
        }
        else {
          proxy.$message({
            message:res.data.msg,
            type:'error'
          })
        }
      })
    } else {
      // 表单验证失败
      proxy.$message({
        message:'请验证您的输入格式',
        type:'warning'
      })
    }
  });
};
</script>

<style lang="scss" scoped>
.login-body{
  height:calc(100vh);
  background-size: cover; /**完全覆盖body区域**/
  background: url('@/assets/login_bg.jpg'); /**@默认指向src目录**/
  display: flex;
  justify-content: right;
  /**.bg{
    flex:1;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
  }**/
  .login-panel{
    width:430px;
    margin-right: 10%;
    margin-top:calc((100vh - 600px)/2);
    .login-register{
      padding:25px;
      background: #ffffff;
      border: 2px solid #3498db;
      border-radius: 5px;
      .login-title{
        text-align:center;
        font-size: 18px;
        font-weight: bold;
        margin-bottom:20px;
      }
      .send-email-panel{
        display: flex;
        width:100%;
        justify-content: space-between;
        .send-email-btn{
          margin-left:5px;
        }
      }
      .rememberMe-panel{
        width:100%;
      }
      .no-account{
        width:100%;
        display: flex;
        justify-content: space-between;
      }
      .op-btn{
        width:100%;
      }
    }
  }
  .check-code-panel{
    width:100%;
    display: flex;
    .check-code{
      margin-left:5px;
      cursor:pointer;
    }
  }
  .login-btn-qq{
    margin-top:20px;
    text-align:center;
    display: flex;
    align-items: center;
    justify-content: center;
    img{
      cursor:pointer;
      margin-left:10px;
      width:20px;
    }
  }
}
</style>